/**
 * 微信支付 - 微信支付订单号查询订单（使用标准微信支付 v3 API）
 */
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const fs = require('fs');
const config = require('../config.js');

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const { transaction_id } = event;
        
        if (!transaction_id) {
            return {
                code: -1,
                msg: '缺少参数：transaction_id'
            };
        }
        
        // 获取微信支付客户端
        const WxPay = require('wechatpay-node-v3');
        
        const merchantPrivateKey = fs.readFileSync(config.MCH_PRIVKEY_PATH, 'utf8');
        const wechatPublicKey = fs.readFileSync(config.PLATFORM_CERT_PATH, 'utf8');
        
        let serialNo = config.SERIAL_NO;
        const wxPay = new WxPay({
            appid: config.APPID,
            mchid: config.MCHID,
            serial_no: serialNo,
            privateKey: merchantPrivateKey,
            publicKey: wechatPublicKey,
        });
        
        // 调用查询订单接口
        const result = await wxPay.queryOrder({ transaction_id });
        
        return {
            code: 0,
            msg: 'success',
            data: result
        };
    } catch (error) {
        console.error('查询订单失败:', error);
        return {
            code: -1,
            msg: '查询订单失败: ' + error.message
        };
    }
};